import os

import requests
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget

import global_config
from ui.Forget_password_window import Forget_password_window
from window.My_pop_up_warning import My_pop_up_warning
from window.My_set_new_password_window import My_set_new_password_window


class My_forget_password_window(QWidget, Forget_password_window):
    close_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.username = ''

        # 设置界面标题、图标等
        base_path = os.path.dirname(__file__)
        base_path = base_path.replace('\\window', '')
        icon_path = os.path.join(base_path, 'icon')
        icon_path = os.path.join(icon_path, 'Python.png')
        self.setWindowTitle('忘记密码')
        icon = QIcon(icon_path)
        self.setWindowIcon(icon)

        self.pop_up_warning = My_pop_up_warning()
        self.set_new_password_window = My_set_new_password_window()
        self.answer1.setPlaceholderText('请输入问题1的答案：')
        self.answer2.setPlaceholderText('请输入问题2的答案：')

        # 信号与槽
        self.cancel_button.clicked.connect(self.cancel)
        self.confirm_button.clicked.connect(self.confirm)

    def set_username(self, username):
        self.username = username
        self.set_new_password_window.set_username(username)

    def confirm(self):
        url = 'http://' + global_config.localhost + ':8000/checkSecurity/'
        params = {
            'username': self.username,
            'ans1': self.answer1.text(),
            'ans2': self.answer2.text()
        }
        result= requests.get(url, params=params).json()
        if result['result'] == 'success':
            self.hide()
            self.answer1.setText('')
            self.answer2.setText('')
            self.set_new_password_window.show()
        elif result['result'] == 'failed':
            self.pop_up_warning.warning_info_label.setText('获取失败')
            self.pop_up_warning.warning_info_text.setText('密保问题答案错误')
            self.pop_up_warning.show()


    def cancel(self):
        self.close()
        self.question1_text.setText('')
        self.question2_text.setText('')
        self.answer1.setText('')
        self.answer2.setText('')
